<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="75%"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-scrollbar max-height="60vh" v-loading="loading">
      <el-form
        ref="formRef"
        class="mr-3"
        :model="formData"
        scroll-to-error
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="任务标题" prop="taskTitle">
          <el-input
            v-model="formData.taskTitle"
            show-word-limit
            :disabled="disabled"
            :maxlength="200"
            @change="handleChangeValue"
          />
        </el-form-item>
        <el-row>
          <el-col :span="6">
            <el-form-item label="交办领导" prop="assignLeader">
              <LeaderSelect
                v-model="formData.assignLeader"
                assignLeaders
                :disabled="disabled"
                @change="handleChangeValue"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交办类型" prop="assignType">
              <DictionarySelect
                v-model="formData.assignType"
                :disabled="disabled"
                parent-dictionary-value="taskType"
                @change="handleChangeValue"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交办时间" prop="assignTime">
              <el-date-picker
                v-model="formData.assignTime"
                type="date"
                :disabled="disabled"
                placeholder="请选择"
                value-format="YYYY-MM-DD 00:00:00"
                format="YYYY年MM月DD日"
                @change="handleChangeValue"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审批状态">
              <TaskShow :status="formData.taskStatus" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input
            v-model="formData.taskDesc"
            type="textarea"
            :disabled="disabled"
            :autosize="{ minRows: 5 }"
            @change="handleChangeValue"
          />
        </el-form-item>
        <el-form-item label="事件列表" prop="matterList">
          <TaskThingTable
            ref="taskThingTable"
            v-model="formData.matterList"
            :task-id="formData.id"
            :task-status="formData.taskStatus"
            :disabled="disabled"
            @refresh="getMatter()"
          />
        </el-form-item>
        <el-form-item v-if="disabled" label="审批意见">
          <el-input
            v-model="formData.processOpinion"
            type="textarea"
            :autosize="{
              minRows: 5,
            }"
            disabled
          />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer flex justify-between items-center">
        <div>
          <el-button
            v-if="!waitApprove && !canChange"
            type="primary"
            :disabled="
              formData.taskStatus === ETaskStatus['审批中'] ||
              formData.taskStatus === ETaskStatus['通过']
            "
            @click="canChange = true"
          >
            编辑
          </el-button>
        </div>
        <div>
          <el-button @click="close">取消</el-button>
          <template v-if="canChange">
            <el-button
              v-if="formData.taskStatus === 1"
              type="primary"
              :loading="loading"
              :disabled="disabled"
              @click="handleBeforeSubmit(formData.taskStatus, 1)"
            >
              暂存
            </el-button>
            <el-button
              type="success"
              :loading="loading"
              :disabled="disabled"
              @click="handleBeforeSubmit(formData.taskStatus, 2)"
            >
              提交
            </el-button>
          </template>
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, useTemplateRef } from 'vue'
import { ElMessageBox, FormInstance, FormRules } from 'element-plus'
import LeaderSelect from '@/components/leader/LeaderSelect.vue'
import DictionarySelect from '@/components/dictionary/DictionarySelect.vue'
import TaskThingTable from '@/views/mission/task/TaskThingTable.vue'
import { InternalRuleItem, Value } from 'async-validator/dist-types/interface'
import { addTask, getMatterList, modifyTask } from '@/api/mission/task'
import TaskShow from '@/components/statusShow/task/TaskShow.vue'
import { ETaskStatus } from '@/components/statusShow/util'
import { Message } from '@/hooks/message'

const emit = defineEmits(['update'])
const formRef = useTemplateRef<FormInstance>('formRef')

const dialogVisible = ref(false)
const loading = ref(false)
const isNew = ref(true)
const canChange = ref(true)
const isChange = ref(false)
const formData = reactive({
  id: null,
  taskTitle: null,
  assignLeader: null,
  assignType: null,
  assignTime: null,
  taskStatus: 1,
  taskDesc: null,
  processOpinion: null,
  matterList: [],
})

const rules = ref<FormRules<typeof formData>>({
  taskTitle: { required: true, message: '请输入任务标题', trigger: 'blur' },
  assignLeader: {
    required: true,
    message: '请选择交办领导',
    trigger: 'change',
  },
  assignType: {
    required: true,
    message: '请选择交办类型',
    trigger: 'change',
  },
  assignTime: {
    required: true,
    message: '请选择交办时间',
    trigger: 'change',
  },
  matterList: {
    required: true,
    validator: validatorMatterList,
    trigger: 'noTrigger',
  },
})

const title = computed(() => {
  if (isNew.value) {
    return '任务登记'
  } else if (canChange.value) {
    return '编辑任务'
  } else {
    return '任务详情'
  }
})

const disabled = computed(() => {
  return !canChange.value || waitApprove.value
})

const waitApprove = computed(() => {
  return formData.taskStatus === 2 || formData.taskStatus === 3
})

function validatorMatterList(
  rule: InternalRuleItem,
  value: Value,
  callback: (error?: string | Error) => void,
) {
  if (Array.isArray(value) && value.length > 0) {
    return callback()
  } else {
    return callback(new Error('请添加事项'))
  }
}

function handleChangeValue() {
  isChange.value = true
}

defineExpose({ show })

async function show(row?: any) {
  dialogVisible.value = true
  if (row) {
    isNew.value = false
    canChange.value = false
    loading.value = true
    Object.assign(formData, {
      id: row.id,
      taskTitle: row.taskTitle,
      assignLeader: row.assignLeader,
      assignType: row.assignType,
      assignTime: row.assignTime,
      taskStatus: row.taskStatus,
      taskDesc: row.taskDesc,
      processOpinion: row.processOpinion,
    })
    await getMatter()
    loading.value = false
  }
}

async function getMatter() {
  const { data } = await getMatterList(formData.id)
  if (data.status === 200) {
    formData.matterList = data.data
  }
}

function close() {
  dialogVisible.value = false
  loading.value = false
  isNew.value = true
  canChange.value = true
  isChange.value = false
  formRef.value.resetFields()
  Object.assign(formData, {
    id: null,
    taskTitle: null,
    assignLeader: null,
    assignType: null,
    assignTime: null,
    taskStatus: 1,
    taskDesc: null,
    processOpinion: null,
    matterList: [],
  })
}

function handleBeforeSubmit(baseStatus: number, newTaskStatus: number) {
  let taskStatus: number
  if (newTaskStatus === 2) {
    taskStatus = 2
  } else {
    taskStatus = baseStatus
  }
  if (newTaskStatus === 2) {
    ElMessageBox.confirm('确定提交进行任务审批吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        submit(taskStatus)
      })
      .catch(() => {})
  } else {
    submit(taskStatus)
  }
}

function submit(taskStatus: number) {
  formRef.value.validate(async (bool) => {
    if (!bool) {
      return
    }

    loading.value = true
    if (!formData.id) {
      const postData = {
        ...formData,
        taskStatus: taskStatus,
      }
      const { data } = await addTask(postData)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        emit('update')
        close()
      }
    } else if (formData.id) {
      const postData = {
        id: formData.id,
        taskTitle: formData.taskTitle,
        assignLeader: formData.assignLeader,
        assignType: formData.assignType,
        assignTime: formData.assignTime,
        taskDesc: formData.taskDesc,
        taskStatus: taskStatus,
      }
      const { data } = await modifyTask(postData)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        emit('update')
        close()
      }
    }
    loading.value = false
  })
}
</script>

<style scoped lang="scss">
:deep(.el-date-editor) {
  width: 100%;
}
</style>
